import store from '../src/store';
import { getStorageToken } from "../src/utils/storageHelper.js";
import { httpUrl } from "./config.js";
import Vue from "vue";

const request = {}
// 这里给content-type设置默认值，可以避免使用时，浏览器强制刷新时，
// 避免6情况content-type变成Content-Type: application/json, application/x-www-form-urlencoded
let headers = {
	'content-type': ''
}

/**
 * 请求列表
 * {
 * key请求别名,
 * url请求地址，请求返回后删除,
 * request请求体
 * }
 */
request.requestTasks = []
request.cancelTask = (url, key) => {
    // 删除全部任务
    if (!url && !key) {
        request.requestTasks.forEach(((requestTask) => {
            try {
                requestTask.task.abort();
            } catch (err) {
            }
        }));
        request.requestTasks = [];
        return;
    }
    // 根据url或者key删除指定任务
    for (let i = 0; i < request.requestTasks.length; i ++) {
        let requestTask = request.requestTasks[i];
        if (
            (url && url == requestTask.url)
            || (key && key == requestTask.key)
        ) {
            try {
                requestTask.task.abort();
            } catch (err) {
            }
            request.requestTasks = request.requestTasks.filter((task) => {
                let flag = (
                    (url && url != requestTask.url)
                    || (key && key != requestTask.key)
                );
                return flag;
            });
            break;
        }
    }
}

/**
 * url请求地址
 * method请求方式「GET、POST、PUT、DELETE、CONNECT、HEAD、OPTIONS、TRACE」
 * data请求参数
 * power请求参数，权限判断 因为有的接口请求头可能需要添加的参数不一样
 * key请求存储关键字，为空时时无法指定取消
 */
request.globalRequest = (url, method, data, power, key) => {
	if (process.env.NODE_ENV != 'development') {
		// 每次都更新定位信息
        try {
            getLocation();
        } catch (e) {
            console.log(e);
        }
	}

    if (url.indexOf(httpUrl) > -1) {
        // 处理轨迹上报的逻辑-综治
        // headers 请求头里面不能有中文
        let _bizId = '';
        if (!!data) {
            _bizId = !!data._bizId ? data._bizId : '';
        }
        // 兼容put提交判断链接中是否有问号 add by ray on 2021/04/20
        let splicing = (url.indexOf('?') != -1) ? '&' : '?';
        url = url + splicing + '_longitude=' + store.state.ldLongitude +
            '&_latitude=' + store.state.ldLatitude +
            '&_bizAddress=' + store.state.ldAddress +
            '&_bizType=BIZNAME' + '&_gisType=01';
        // 兼容put提交判断链接中是否有问号 add by ray on 2021/04/20
        if (url.indexOf('_bizId=') == -1) {
            url = url + '&_bizId=' + _bizId;
        }
    }

	/*
        权限判断 因为有的接口请求头可能需要添加的参数不一样，所以这里做了区分
        1 == 综治平台接口 支持put请求
        2 == 块数据接口
        3 == 不需要参数的接口
        4 == 综治平台接口 delete请求
        5 == 新块数据接口
        6 == 综治平台接口 post请求 数据data
    */
    // 默认不设置headers
    for(let key of Object.keys(headers)){
        Vue.delete(headers, key);
    }

	switch (power) {
		case 1:
			headers['accessToken'] = getStorageToken("loginToken")
			break;
		case 2:
			headers['token'] = store.state.dataToken
			headers['content-type'] = 'application/x-www-form-urlencoded'
			break;
		case 3:
			headers['content-type'] = 'application/x-www-form-urlencoded'
			break;
		case 4:
			headers['accessToken'] = getStorageToken("loginToken")
			headers['content-type'] = 'application/json;charset=UTF-8'
			break;
		case 5:
			headers['content-type'] = 'application/x-www-form-urlencoded'
			data['GTOKEN'] = 'E5CBEF6965F37DC24B04B3543D0BBB29'
			break;
		case 6:
			headers['accessToken'] = getStorageToken("loginToken")
			headers['content-type'] = 'application/x-www-form-urlencoded'
			break;
        case 7:
            if (data && data.token) {
                headers['token'] = data.token
            }
            headers['content-type'] = 'application/x-www-form-urlencoded'
            break;
		default:

			break;
	}

	let requestTask = uni.request({
		url: url,
		method,
		data: data,
		dataType: 'json',
		header: headers
	}).then(res => {
        request.cancelTask(url);
		if (
            !!res[1] && res[1].statusCode == 200
            || (res[1].data.state || res[1].data.success)
            || (res[1].data.code == 200 || res[1].data.retCode == '00000')
        ) {
			return res[1].data
		} else {
			throw res[1]
		}
    }).catch(parmas => {
        request.cancelTask(url);
        uni.hideLoading();
		if (parmas.statusCode != 200) {
			uni.showToast({
				title: '系统内部错误！',
				icon: 'none'
			})
		} else if (parmas && parmas.errMsg == 'request:fail timeout') {
            // 请求时间设置在manifest.json文件中 networkTimeout属性设置  目前为10000ms
			uni.showToast({
				title: '请求超时，请重试！',
				icon: 'none'
			})
		} else {
			uni.showToast({
				title: parmas.data.msg || parmas.data.retMsg || parmas.data.message,
				icon: 'none'
			})
		}
		// switch (parmas.code) {
		// 	case 401:
		// 		uni.clearStorageSync()
		// 		break
		// 	default:
		// 		uni.showToast({
		// 			title: parmas.message,
		// 			icon: 'none'
		// 		})
		// 		return Promise.reject()
		// 		break
		// }
	});

    request.requestTasks.push({
        key: key || "",
        url: url || "",
        task: requestTask,
    });
    return requestTask;
}

/**
 * @description: 定位 获取经纬度-链动
 */
function getLocation() {
	// window.app.ext.getLocation({
	// 	callback: (res) => {
	// 		let list = gcj02towgs84(parseFloat(res.data.longitude), parseFloat(res.data.latitude));
	// 		store.commit("updateLocalLdLongitude", list[0]);
	// 		store.commit("updateLocalLdLatitude", list[1]);
	// 		store.commit("updateLocalLdAddress", res.data.address);
	// 	}
	// });
}

export default request
